package com.hejiale.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hejiale.lease.common.constant.RedisConstant;
import com.hejiale.lease.common.exception.LeaseException;
import com.hejiale.lease.common.result.ResultCodeEnum;
import com.hejiale.lease.common.utils.JwtUtil;
import com.hejiale.lease.common.utils.SMSUtil;
import com.hejiale.lease.model.entity.UserInfo;
import com.hejiale.lease.model.enums.BaseStatus;
import com.hejiale.lease.web.app.mapper.UserInfoMapper;
import com.hejiale.lease.web.app.service.LoginService;
import com.hejiale.lease.web.app.vo.user.LoginVo;
import com.hejiale.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    private final Client smsClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    public LoginServiceImpl(Client smsClient) {
        this.smsClient = smsClient;
    }

    @Override
    public void getCode(String phone) {
        if (phone == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

        // 初始化SMSUtil
        SMSUtil.init(smsClient,stringRedisTemplate);

        // 判断是否已经发送验证码，即Redis中是否存在该手机号
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            // 判断验证码是否过期
            SMSUtil.isExpired(phone);
            // 禁止频繁发送验证码
            SMSUtil.isTooOften(phone);
        }

        // 生成验证码
        String code = SMSUtil.getVerifyCode(6);
        SMSUtil.sendSMS(phone, code);

        // 将验证码存入redis中，并设置过期时间
        stringRedisTemplate.opsForValue().set(key , code , RedisConstant.APP_LOGIN_CODE_TTL_SEC , TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        // 初始化SMSUtil
        SMSUtil.init(smsClient, stringRedisTemplate);

        // 判断手机号和验证码是否为空
        if (loginVo.getPhone() == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }else if (loginVo.getCode() == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        // 判断验证码是否过期
        SMSUtil.isExpired(loginVo.getPhone());

        // 判断验证码是否匹配
        SMSUtil.isCorrect(loginVo.getCode(), loginVo.getPhone());

        // 获取用户信息
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, loginVo.getPhone()));

        // 注册
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setNickname("用户-" + loginVo.getPhone().substring(6));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoMapper.insert(userInfo);
        }else if(userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());//
    }

    @Override
    public UserInfoVo getUserInfoById(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }
}
